package control.admin;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.User;
import persistence.PersistenceFactory;
import persistence.PersistenceInterface;

public class CreateClientServlet extends CoolServlet {

    @Override
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        PersistenceInterface persistenceManager = PersistenceFactory.getInstance(persistenceMechanism);
        User user = generateClientFromRequest(request);

        if (user != null && persistenceManager.createUser(user)) {
            gotoURL(loginform, request, response);
            request.setAttribute("resultado","Congratulation, your account is created");
        } else {
            request.getRequestDispatcher("forms/CreateNewClientForm.jsp").forward(request, response);
        }
    }

    User generateClientFromRequest(HttpServletRequest request) {
        User user;
        String name = request.getParameter("name");
        String username = request.getParameter("username");
        String address = request.getParameter("address");
        String pass = request.getParameter("pass");
        //char status = request.getParameter("status").charAt(0);
        String status = request.getParameter("status");
        String formadepago = request.getParameter("formatdepago");

        if (!validateForm(request)) {
            request.setAttribute("resultado", "Username and name should be only letter");
            return null;
        } else if ( (!validateName(name)) || (!validateName(username)) ) {
            request.setAttribute("resultado", "tienes que llenar todos los campos");
            return null;
        } else {
            user = new User(name, address, username, formadepago, pass, status);
            return user;
        }
    }

    private boolean validateForm(HttpServletRequest request) {
        if (!"".equals(request.getParameter("name"))
                && !"".equals(request.getParameter("address"))
                && !"".equals(request.getParameter("username"))
                && !"".equals(request.getParameter("pass"))) {
            return true;
        }
        return false;
    }

    private boolean validateName(String name) {
        String namePattern = "[a-zA-Z]+";
        return name.matches(namePattern);
    }
}
